<template>
  <!-- preset="card" -->
  <n-modal v-model:show="showModal" style="width: 800px; max-width: 90vw">
    <div class="model-container">
      <div class="model-content">
        <div class="model-title-box">
          <div class="icon-title-legend"></div>
          <div class="title-text">新建设防作业</div>
          <div class="close-box" @click="closeModal"></div>
        </div>
        <div class="content-box">
          <job-entering-form
            ref="jobEnteringFormRef"
            :direction-options="directionOptions"
            :track-options="trackOptions"
            :group-options="groupOptions"
          />
        </div>
        <div class="btn-box">
          <n-button type="success" @click="handleSubmit">确定</n-button>
          <n-button type="info" @click="closeModal">取消</n-button>
        </div>
      </div>
    </div>
  </n-modal>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { useMessage } from 'naive-ui';
  import JobEnteringForm from './jobEnteringForm.vue';
  import { getGroupList } from '@/api/home/group';
  import { getTrackPage } from '@/api/business/stationManager/track';
  import { getStationByOrgId } from '@/api/business/stationManager/station';
  import { addDefensiveTask } from '@/api/home/defensive';

  // 定义组件属性和事件
  const emit = defineEmits<{
    (e: 'refresh'): void;
  }>();

  // 响应式数据
  const showModal = ref(false);
  const jobEnteringFormRef = ref();
  const orgId = ref<string>('');
  const directionOptions = ref<Array<{ value: string; label: string }>>([]);
  const trackOptions = ref([]);
  const groupOptions = ref([]);

  // 消息提示
  const message = useMessage();

  // 显示模态框
  function show(orgIdParam: string) {
    orgId.value = orgIdParam;
    showModal.value = true;

    // 加载数据
    loadStationData();
    loadTrackData();
    loadGroupData();
  }

  // 关闭模态框
  function closeModal() {
    showModal.value = false;
  }

  // 加载站点数据（用于方向选项）
  async function loadStationData() {
    try {
      const res = await getStationByOrgId({ orgId: orgId.value });
      if (res && res.direction) {
        if (res.direction === '1') {
          directionOptions.value = [
            { value: res.directionEast, label: res.directionEast },
            { value: res.directionWest, label: res.directionWest },
          ];
        } else {
          directionOptions.value = [
            { value: res.directionSouth, label: res.directionSouth },
            { value: res.directionNorth, label: res.directionNorth },
          ];
        }
      }
    } catch (error) {
      console.error('加载站点数据失败:', error);
    }
  }

  // 加载股道数据
  async function loadTrackData() {
    try {
      const res = await getTrackPage({
        currentPage: 1,
        pageSize: 999,
        orgId: orgId.value,
      });
      trackOptions.value = res.records || [];
    } catch (error) {
      console.error('加载股道数据失败:', error);
    }
  }

  // 加载班组数据
  async function loadGroupData() {
    try {
      const res = await getGroupList({
        currentPage: 1,
        pageSize: 999,
        orgId: orgId.value,
      });
      groupOptions.value = res.records || [];
    } catch (error) {
      console.error('加载班组数据失败:', error);
    }
  }

  // 提交表单
  async function handleSubmit() {
    try {
      // 获取表单数据
      const formData = await jobEnteringFormRef.value.submit();

      // 验证子表单
      let isValid = true;
      try {
        if (jobEnteringFormRef.value.formElRef) {
          for (const form of jobEnteringFormRef.value.formElRef) {
            await form.validate();
          }
        }
      } catch (error) {
        isValid = false;
      }

      // 如果验证通过，提交数据
      if (formData && isValid) {
        formData.groupAndTaskList = jobEnteringFormRef.value.formChild;
        await addDefensiveTask(formData);
        message.success('设防任务创建成功');
        closeModal();
        emit('refresh');
      }
    } catch (error) {
      message.error('操作失败: ' + (error as Error).message);
    }
  }

  // 暴露方法给父组件
  defineExpose({
    show,
    close: closeModal,
  });
</script>

<style scoped>
  @import './setDefenseModel.css';
  @import './fontEnhance.css';
</style>
